/**
 * 安全地将源对象的属性合并到目标对象中
 * 只更新目标对象中已存在的键，使用目标对象的原值作为默认值
 * @param target 目标对象 (会被修改)
 * @param source 源对象
 * @returns 合并后的目标对象
 */
function safeMergeObject<T extends Record<string, any>>(
  target: T, 
  source: Partial<T> | Record<string, any>
): T {
  Object.assign(target, Object.fromEntries(
    (Object.keys(target) as Array<keyof T>).map(key => [
      key,
      (source as Record<keyof T, any>)[key] ?? target[key]
    ])
  ))
  return target
}

/**
 * 创建一个新对象，安全地合并源对象到目标对象中
 * 只包含目标对象中已存在的键，使用目标对象的原值作为默认值
 * @param target 目标对象模板
 * @param source 源对象
 * @returns 新的合并对象
 */
function createMergedObject<T extends Record<string, any>>(
  target: T, 
  source: Partial<T> | Record<string, any>
): T {
  return Object.fromEntries(
    (Object.keys(target) as Array<keyof T>).map(key => [
      key,
      (source as Record<keyof T, any>)[key] ?? target[key]
    ])
  ) as T
}

export {
  safeMergeObject,
  createMergedObject
} 
